<?php
header('Content-Type: text/plain');
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
session_name(SESSION);
session_start();
$myPdo = DbUtils::createPdoInst();
$action = $_POST['action'];
try {
  $myPdo->beginTransaction();
  switch ($action) {
    case 'remove':
      remove($myPdo);
      break;
    default:
      break;
  }
  $myPdo->commit();
} catch (PDOException $e) {
  echo $e->getMessage();
}

function remove($myPdo) {
  if (!isset($_SESSION[ADMIN])) {
    return;
  }
  $q = json_decode(MiscUtils::getParam('q', '[]'));
  $cond_vals = new stdClass();
  $cond_vals->c = 't.sys_id = :v1';
  $cond_vals->v = array(':v1' => $q->id);
  $pages = DbUtils::get($myPdo, 'pz2_page', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
  foreach ($pages as &$page) {
    $cond_vals = new stdClass();
    $cond_vals->c = 'page_id = :v1';
    $cond_vals->v = array(':v1' => $page->id);
    DbUtils::deleteByCond($myPdo, 'pz2_plugin_instance', $cond_vals);
  }
  $cond_vals = new stdClass();
  $cond_vals->c = 'sys_id = :v1';
  $cond_vals->v = array(':v1' => $q->id);
  DbUtils::deleteByCond($myPdo, 'pz2_page', $cond_vals);
  if (file_exists('../../../' . $q->script . '.php')) {
    unlink('../../../' . $q->script . '.php');
  }
  DbUtils::delete($myPdo, 'pz2_sys', $q);
  echo json_encode(array());
}
?>